<template>
  <div class="article-category-page">
    <div class="page-header">
      <h2 style="font-weight: 700;">文章分类</h2>
      <el-button type="primary" @click="addCategoryDialogVisible = true">添加文章分类</el-button>
    </div>

    <el-table :data="tableData" border style="width: 100%; margin-top: 20px;">
      <el-table-column prop="categoryId" label="ID"></el-table-column>
      <el-table-column prop="categoryName" label="名称"></el-table-column>
      <el-table-column prop="sort" label="排序"></el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 20, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="margin-top: 20px; text-align: right;"
    ></el-pagination>

    <!-- 编辑分类模态框 -->
    <el-dialog
      v-model="UpdateCategoryDialogVisible"
      :title= "编辑文章分类"
      width="500px"
    >
      <el-form :model="form" label-width="100px">
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="form.categoryName" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model.number="form.sort" placeholder="请输入排序值" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="UpdateCategoryDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveCategory">确认</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- ====================================================================================== -->
    <!-- 通用：新增/编辑分类模态框 -->
<el-dialog
  v-model="addCategoryDialogVisible"
  :title="新增分类"
  width="500px"
>
  <el-form :model="addform" label-width="100px">
    <el-form-item label="分类名称" prop="categoryName">
      <el-input v-model="addform.categoryName" placeholder="请输入分类名称" />
    </el-form-item>
    <el-form-item label="排序" prop="sort">
      <el-input v-model.number="addform.sort" placeholder="请输入排序值" />
    </el-form-item>
  </el-form>
  <template #footer>
    <div class="dialog-footer">
      <el-button @click="addCategoryDialogVisible=false">取消</el-button>
      <el-button type="primary" @click="addCategory">确认</el-button>
    </div>
  </template>
</el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import httpInstance from '@/utils/http';

const tableData = ref([]);
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);
const UpdateCategoryDialogVisible = ref(false);
// 新增：控制新增模态框显示/隐藏
const addCategoryDialogVisible = ref(false);
const isEdit = ref(false);
const form = reactive({
  categoryId: '',
  categoryName: '',
  sort: 100
});

const addform = reactive({
  categoryName: '',
  sort: 100
});

// 分页方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchCategoryList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchCategoryList();
};

// 获取分类列表 - 移除加载中提示
const fetchCategoryList = async () => {
  try {
    // 正确调用分页接口
    const { data: res } = await httpInstance.post(
      `/eduservice/articleCategory/page/${currentPage.value}/${pageSize.value}`
    );
    // 打印完整响应，用于调试数据结构
    console.log('完整响应数据:', res);

    tableData.value =res.data.list
    total.value = res.data.total;

  } catch (error) {
    ElMessage.error('获取分类列表失败，请重试');
  }
};

//编辑弹窗
const handleEdit = (row) => {
 UpdateCategoryDialogVisible.value = true;
 getCategoryById(row.categoryId)
};

// 新增分类
const addCategory = async () => {
  if (!addform.categoryName.trim()) {
    ElMessage.warning('请输入分类名称');
    return;
  }
  try {
    await httpInstance.post('/eduservice/articleCategory/AddArticleCategory', addform);
    ElMessage.success('添加成功');
    addCategoryDialogVisible.value = false;
    fetchCategoryList(); // 刷新列表
  } catch (error) {
    console.error('添加失败:', error);
    ElMessage.error('添加失败，请重试');
  }
};

// 删除分类
const deleteCategory = async (id) => {
  const response = await httpInstance.delete(`/eduservice/articleCategory/${id}`);
  return response.data;
};


// 页面加载时获取数据
onMounted(() => {
  fetchCategoryList();
});

// 点击编辑按钮时，将当前行数据填充到表单中
const getCategoryById = async (id) => {
  const { data: res } = await httpInstance.get(`/eduservice/articleCategory/${id}`);
  console.log('当前行数据:', res);
  // 修复：直接赋值后端返回的 categoryId
  form.categoryId = res.data.category.categoryId;
  form.categoryName = res.data.category.categoryName;
  form.sort = res.data.category.sort;
};

// 更新分类
const saveCategory = async () => {
  if (!form.categoryName.trim()) {
    ElMessage.warning('请输入分类名称');
    return;
  }
  try {
    await httpInstance.put('/eduservice/articleCategory', form);
    ElMessage.success('编辑成功');
    UpdateCategoryDialogVisible.value = false;
    fetchCategoryList(); // 刷新列表
  } catch (error) {
    console.error('编辑失败:', error);
    ElMessage.error('编辑失败，请重试');
  }
};

// 删除分类
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该分类吗？删除后不可恢复',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    await deleteCategory(row.categoryId);
    ElMessage.success('删除成功');
    fetchCategoryList(); // 刷新列表
  } catch (error) {
    if (error.type !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};

</script>

<style scoped>
.article-category-page {
  padding: 20px;
  min-height: 500px; /* 确保分页始终可见 */
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
/* 确保分页组件在数据为空时也能显示 */
:deep(.el-pagination) {
  display: flex;
  flex-wrap: wrap;
  padding: 10px 0;
}
</style>